using System;
using System.Collections.Generic;
using System.Text;

namespace Schemata.Core
{
    /// <summary>
    /// Represents a database.
    /// </summary>
    public class DatabaseSchema : GenericSchema
    {
        private string _connectionString;
        private SchemaProvider _provider;
        
        /// <summary>
        /// Gets or sets the connection string.
        /// </summary>
        /// <value>The connection string.</value>
        public string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }
        
        /// <summary>
        /// Gets or sets the provider.
        /// </summary>
        /// <value>The provider.</value>
        public SchemaProvider Provider
        {
            get { return _provider; }
            set { _provider = value; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DatabaseSchema"/> class.
        /// </summary>
        /// <param name="databaseName">Name of the database.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="connectionString">The connection string.</param>
        public DatabaseSchema(string databaseName , SchemaProvider provider, string connectionString)
        {
            if (string.IsNullOrEmpty(databaseName))
                throw new ApplicationException("databaseName cannot be null or empty.");

            if (provider.GetType() != typeof(SqlServerSchemaProvider))
                throw new NotImplementedException("Currently we only support the SqlServerProvider");

            if (string.IsNullOrEmpty(connectionString))
                throw new ApplicationException("connectionString cannot be null or empty.");

            Name = databaseName;
            Provider = provider;
            ConnectionString = connectionString;
        }

        /// <summary>
        /// Gets the table schema by name.
        /// </summary>
        /// <param name="tableName">Name of the table.</param>
        /// <returns></returns>
        public TableSchema GetTableSchemaByName(string tableName)
        {
            TableSchema result = null;

            foreach (TableSchema tableSchema in Tables)
            {
                if (tableSchema.Name == tableName)
                {
                    result = tableSchema;
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// Gets the tables.
        /// </summary>
        /// <value>The tables.</value>
        public List<TableSchema> Tables
        {
            get { return Provider.GetTables(this); }
        }
    }
}
